﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Caching;
using System.Data.SqlClient;

namespace OTPlus.Core.Storage
{
    //Represents a collection of thread summaries for display in the forum view. Also handles caching for those items.
    public class ThreadSummaryCache: List<ThreadSummaryItem>
    {

        #region Singleton
        private static ThreadSummaryCache instance;

        private ThreadSummaryCache() { }

        public static ThreadSummaryCache Instance
        {
            get 
            {
                if (instance == null)
                {
                    instance = new ThreadSummaryCache();
                }
                return instance;
            }
        }
        #endregion


        public ThreadSummaryCache AccessCacheData()
        {

            ObjectCache cache = MemoryCache.Default;
            if (!cache.Contains("ThreadSummaryData"))
            {
                CacheItemPolicy cip = new CacheItemPolicy();
                cip.Priority = CacheItemPriority.NotRemovable; 
                cache.Add("ThreadSummaryData", new ThreadSummaryCache(), cip);
                loadEmptyData();
            }

            return (ThreadSummaryCache)cache.Get("ThreadSummaryData");
        }

        public void AddActivities(List<Content.Activity> activityList)
        {
            //we can't add to the cache list as we're iterating over it, so we'll
            //add everything to this list, then add this list to the cache.
            List<ThreadSummaryItem> listToAdd = new List<ThreadSummaryItem>();

            foreach(Content.Activity activity in activityList)
            {
                bool existsInCache = false;

                if (this.AccessCacheData().Count > 0)
                { existsInCache = this.AccessCacheData().Any(p => p.ActivityID == activity.ID); }

                if (!existsInCache)
                { listToAdd.Add(new ThreadSummaryItem(activity)); }
            }

            this.AccessCacheData().AddRange(listToAdd);
        }
        
        private void loadEmptyData()
        { 
            ThreadSummaryItem tsi = new ThreadSummaryItem();
            tsi.ActivityID = "fatglen";
            tsi.Replies = 0;
            tsi.Title = "Cache is empty, glen is fat. yin/yang";
            tsi.ActorName = "otplus system";

            this.AccessCacheData().Add(tsi);
        }

    }
}